package myJs.implicits

import myJs.Implicits._
import myJs.Utils.layer
import myJs.myPkg.{SwalOptions, swal}

import scala.concurrent.{Future, Promise, TimeoutException}
import scala.concurrent.duration.{DurationInt, FiniteDuration}
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

/**
 * Created by Administrator on 2020/1/16
 */
trait MyFutureTool {

  implicit class MyFuture[T](f: Future[T]) {

    def withTimeout(timeout: FiniteDuration) = {
      val p = Promise[T]()
      val timeoutHandle = js.timers.setTimeout(timeout) {
        p.tryFailure(new TimeoutException)
      }
      f.onComplete { result =>
        p.tryComplete(result)
        js.timers.clearTimeout(timeoutHandle)
      }
      p.future
    }

    def timeoutDeal(index: Int) = {
      f.withTimeout(60.seconds).onComplete {
        case Failure(e) =>
          layer.close(index)
          swal(SwalOptions(title = "错误", text = "运行时间过长，请刷新页面!", `type` = "error"))
          println(e.getMessage)
        case Success(x) =>
      }
    }

    def timeoutDeal = {
      f.withTimeout(60.seconds).onComplete {
        case Failure(e) =>
          swal(SwalOptions(title = "错误", text = "运行时间过长，请刷新页面!", `type` = "error"))
          println(e.getMessage)
        case Success(x) =>
      }
    }

  }

}
